/* eslint-disable no-undef */
const user = require('../../model/user/user');
const role = require('../../model/user/role');
const { Op } = require('sequelize');
const jwt = require('jsonwebtoken');
const config = require('../../config');
const Rule = require('../../model/user/rule');
const { getTime } = require('../../utils/gettime');
const { nanoid } = require('nanoid');
const Sequelize = require('sequelize');



// const {get} = require("../utils/operation")


// 登录
exports.dologin = async ({ username, password }) => {
    console.log(username, password);
    try {
        const userData = await user.findOne({
            attributes: ['password', 'username'],
            where: { username }
        });
        if (userData) {
            let newPassword = jwt.verify(userData.password, config.jwt.secret);
            let token = jwt.sign(userData.username, config.jwt.secret) + '@' + userData.password + nanoid();
            if (newPassword === password) {
                const res = await user.findOne({
                    attributes: ['username', 'nickname', 'id', 'sex', 'phone', 'mail', 'effect', 'status', 'avatar', 'role_id', 'islogin'],
                    where: { username },
                    include: [{
                        model: role,
                        attributes: ['rolename', 'rolekey', 'creator', 'id']
                    }]
                });
                if (res) return { msg: '登陆成功', code: '200', data: res, token };
                return { msg: '登陆失败1', code: '400' };
            } else {
                return { msg: '登陆失败2 密码不正确', code: '400' };
            }
        } else {
            return { msg: '登陆失败3 请输入正确的用户名或密码', code: '400' };
        }
    } catch (err) { return { msg: '登陆失败', code: '400', err }; }
};

// 注册
exports.createuser = async ({ nickname, username, password, creator, role_id, phone, mail, sex }) => {
    try {
        let isCreate = await user.findOne({ where: { username } });
        // 如果已有该用户 且该用户状态为 true 则 将该用户状态设置为 false
        if (isCreate) {
            let userStatus = await user.findOne({ where: { username }, attributes: ['status'] });
            // return userStatus
            if (userStatus.status) {
                newData.status = false;
                newData.role_id = role_id;
                let editStatus = await user.update(newData, { where: { username } });
                // return editStatus
                if (editStatus) return { msg: '已将此用户设置为有效', code: '200' };
                return { msg: '添加用户失败', code: '400' };
            } else {
                return { msg: '重复的用户名', code: '400' };
            }
        } else {
            let newData = {};
            newData.username = username;
            newData.nickname = nickname;
            newData.creator = creator;
            if (role_id) newData.role_id = role_id;
            if (phone) newData.phone = phone;
            if (mail) newData.mail = mail;
            if (sex) newData.sex = sex;

            newData.createdate = getTime();
            let newPassword = jwt.sign(password, config.jwt.secret);
            newData.password = newPassword;

            let create = await user.create(newData);
            if (create) return { msg: '添加用户成功', code: '200' };
            return { msg: '添加用户失败', code: '400' };
        }
    } catch (err) { return { msg: '添加用户失败', code: '400', err }; }
};

// 修改用户资料
exports.edituser = async ({ nickname, id, sex, phone, mail, effect, status, role_id }) => {
    try {
        let newData = {};
        // 传递哪个更新哪个
        if (sex) { newData.sex = sex; }
        if (phone) {
            newData.phone = phone;
        }
        if (mail) {
            newData.mail = mail;
        }
        if (effect) { newData.effect = effect; }
        if (nickname) { newData.nickname = nickname; }
        if (status) { newData.status = status; }
        if (role_id) { newData.role_id = role_id; }
        newData.updated = getTime();
        // 更新
        const res = await user.update(newData, {
            where: { id }
        });
        if (res) {
            const data = await user.findOne({
                attributes: ['username', 'sex', 'phone', 'mail', 'effect', 'status', 'avatar', 'updated', 'updator'],
                where: { id }
            });
            return { msg: '编辑用户信息成功', code: '200', data };
        }
        return { msg: '编辑用户信息失败', code: '400' };
    } catch (err) { return { msg: '编辑用户信息失败', code: '400', err }; }
};

// 修改密码
exports.editpass = async ({ id, newpassword, username, password }) => {
    console.log(id, newpassword, username, password);
    try {
        newpassword = jwt.sign(newpassword, config.jwt.secret);
        let isUpd = await user.findOne({ where: { id, username } });
        let newPassword = jwt.verify(isUpd.password, config.jwt.secret);
        if (newPassword !== password) return { msg: '修改密码失败 旧密码错误', code: '400' };
        let res = await user.update({ password: newpassword }, { where: { id } });
        if (res) return { msg: '修改密码成功', code: '200' };
        return { msg: '修改密码失败', code: '400', };
    } catch (err) { return { msg: '修改密码失败', code: '400', err }; }
};

// 获取用户列表
exports.getuserlist = async ({ pageNum, pageSize }) => {
    // try {
    let res = await user.findAndCountAll({
        offset: pageNum * pageSize - pageSize,
        limit: pageSize,
        attributes: [Sequelize.col('role.rolename'), 'id', 'nickname', 'username', 'sex', 'phone', 'mail', 'creator', 'effect', 'status', 'avatar'],
        include: [{
            model: role,
            attributes: []
        }],
        raw: true
    });
    // res.rows.forEach(item => item.role ? item.rolename = item.role.rolename : item.rolename = "暂无角色信息")
    // res.rows.forEach(item => item.aaaaaaaaaaaaaaaaaaa = 1)

    return { msg: '获取用户列表成功', code: '200', data: res };
    // } catch (err) { return { msg: "获取用户列表失败", code: "400", err } }
};

// 根据id查询用户
exports.getuser = async ({ id }) => {
    try {
        let res = await user.findOne({
            attributes: ['id', 'nickname', 'username', 'role_id', 'sex', 'phone', 'mail', 'creator', 'effect', 'status', 'avatar'],
            where: { id },
            include: [{
                model: role,
                attributes: ['rolename', 'creator', 'id'],
                include: [{
                    model: Rule,
                    attributes: ['rulename', 'id', 'summary']
                }]
            }]
        });
        return { msg: '获取用户信息成功', code: '200', data: res };
    } catch (err) { return { msg: '获取用户信息失败', code: '400', err }; }
};

// 模糊查询
exports.getuserbyname = async ({ nickname, pageNum, pageSize }) => {
    try {
        let res = await user.findAndCountAll({
            offset: pageNum * pageSize - pageSize,
            limit: pageSize,
            attributes: ['id', 'username', 'nickname', 'sex', 'phone', 'mail', 'creator'],
            where: {
                nickname: {
                    [Op.like]: `%${nickname}%`
                }
            }
        });
        return { msg: '查询用户成功', code: '200', data: res };
    } catch (err) { return { msg: '查询用户失败', code: '200', err }; }
};

// 删除用户
exports.remove = async ({ id, updator }) => {
    try {
        let res = await user.update({
            status: true,
            updated: getTime(),
            updator
        }, { where: { id } });
        if (res) return { msg: '删除成功', code: '200' };
        return { msg: '删除失败', code: '400' };
    } catch (err) { return { msg: '删除失败', code: '400', err }; }
};

// 激活用户
exports.activation = async ({ id, updator }) => {
    try {
        let res = await user.update({
            status: false,
            updated: getTime(),
            updator
        }, { where: { id } });
        if (res) return { msg: '激活成功', code: '200' };
        return { msg: '激活失败', code: '400' };
    } catch (err) { return { msg: '激活失败', code: '400', err }; }
};
